import {Component, EventEmitter, OnInit, Output, ViewChild} from '@angular/core';
import {FormBuilder, FormGroup, Validators} from '@angular/forms';
import {NzMessageService} from 'ng-zorro-antd/message';
import {FacilityService} from '../../service/facility.service';
import {SharedModule} from '../shared.module';
import {FacilityForm} from '../../types/req/FacilityForm';
import {MODAL_WIDTH} from '../../const'
import {BuildingSelectorComponent} from '../building/building-selector.component';

@Component({
  selector: 'facility-add',
  imports: [
    BuildingSelectorComponent,
    SharedModule
  ],
  templateUrl: './facility-add.component.html',
  standalone: true
})
export class FacilityAddComponent implements OnInit {
  facilityToSave:FacilityForm = {};
  facilityForm!: FormGroup;
  isVisible: boolean = false
  saveLoading: boolean = false
  title: string = '新增公共设施信息'
  modalWidth: string = MODAL_WIDTH

  @ViewChild(BuildingSelectorComponent, { static: false }) buildingSelectorComponent!: BuildingSelectorComponent;

  @Output() addedEvent = new EventEmitter<boolean>();

  constructor(
    private fb: FormBuilder,
    private message: NzMessageService,
    private facilityService: FacilityService
  ) {}

  ngOnInit(): void {
    this.facilityForm = this.fb.group({
      name: [''],
      buildingId: [0],
      buildingName: [''],
      location: [''],
      lastMaintenanceDate: [''],
      status: [undefined],
    })
  }

  onSave() {
    try {
      this.saveLoading = true
      for (const i in this.facilityForm.controls) {
        this.facilityForm.controls[i].markAsDirty();
        this.facilityForm.controls[i].updateValueAndValidity();
      }
      if (!this.facilityForm.valid) {
        this.saveLoading = false
        return
      }
      this.facilityService.save(Object.assign(this.facilityToSave, this.facilityForm.value)).subscribe({
        next: (resp) => {
          if (!resp || resp.code !== 1) {
            this.message.error(resp && resp.msg ? resp.msg : '操作异常')
            return
          }
          this.message.success("保存成功")
          this.onBack(true)
        },
        complete: () => {
          this.saveLoading = false
        }
      })
    } catch (e) {
      console.log('获取数据异常', e)
    }
  }

  onReset() {
    this.title = '新增公共设施信息'.slice()
    this.facilityForm.reset()
  }

  onBack(addedFlag=false) {
    this.isVisible = false
    this.addedEvent.emit(addedFlag);
  }

  display(id: number) {
    this.isVisible = true
    if (id) {
      this.title = '修改公共设施信息'
      this.saveLoading = true
      this.facilityService.findById(id).subscribe({
        next: (resp) => {
          if (resp && resp.code === 1 && resp.data) {
            this.facilityToSave = resp.data
            this.facilityForm.patchValue(this.facilityToSave);
          }
        },
        complete: () => {
          this.saveLoading = false
        }
      })
    } else {
      this.onReset()
    }
  }

  findBuilding() {
    this.buildingSelectorComponent.display()
  }

  handleBuildingSelectedEvent(selectedBuilding: { buildingId?: number; buildingName?: string; }) {
    if (selectedBuilding && 'buildingId' in selectedBuilding) {
      this.facilityForm.patchValue(selectedBuilding);
    }
  }
}
